export class FileUtil {
    static download(response: { data: any, headers: any }) {
        // 文件下载
        const { data, headers } = response
        const fileName = FileUtil.getFileName(response)
        // 此处当返回json文件时需要先对data进行JSON.stringify处理，其他类型文件不用做处理
        debugger
        const blob = new Blob([data], { type: headers['content-type'] });
        FileUtil.downloadByBlob(blob, fileName)
    }

    static downloadByBlob(blob: Blob, fileName: string) {
        const aLink = document.createElement("a");
        aLink.href = URL.createObjectURL(blob);
        aLink.setAttribute('download', fileName);
        aLink.click();
    }

    static getFileName(response: any) {
        try {
            if (!response || !response.headers) return ''
            let c = response.headers['content-disposition']
            if (!c) {
                for (let k in response.headers) {
                    if (response.headers[k] && response.headers[k].indexOf(`attachment;filename*=utf-8''`) != -1) {
                        c = response.headers[k]
                    }
                }
            }
            if (!c) return ''
            return decodeURIComponent(c.replaceAll(`attachment;filename*=utf-8''`, ''))
        } catch (e) {
            return ''
        }
    }

}